package main

import (
	"fmt"
	"strconv"
)

func main() {
	numericalToString()
	stringToNum()
}

// string转数值 strconv.ParseXXX()
func stringToNum() {
	var str3 string = "true"
	var b1 bool
	b1, _ = strconv.ParseBool(str3)
	fmt.Printf("type is : %T  value is :%v\n", b1, b1) //type is : bool  value is :true

	var str1 string = "10"
	var n1 int64
	n1, _ = strconv.ParseInt(str1, 10, 64)
	fmt.Printf("type is : %T  value is :%v\n", n1, n1) //type is : int64  value is :10

	str2 := "20.0"
	var f1 float64
	f1, _ = strconv.ParseFloat(str2, 64)
	fmt.Printf("type is: %T value is: %v\n", f1, f1) //type is: float64 value is: 20

	//注意，这种会直接转为0
	var str4 string = "hello"
	var h1 int64
	h1, _ = strconv.ParseInt(str4, 10, 64)
	fmt.Printf("type is: %T, value is: %v\n", h1, h1) //type is: int64, value is 0

	//注意，这种会直接转为false
	var str5 string = "tom"
	var b2 bool = true
	b2, _ = strconv.ParseBool(str5)
	fmt.Printf("type is : %T  value is: %v\n", b2, b2) //type is : bool  value is: false

	atoi, err := strconv.Atoi("100")
	if err != nil {
		fmt.Println("atoi error:", err)
	} else {
		fmt.Printf("type is : %T  value is: %v\n", atoi, atoi) //type is : int  value is: 100
	}
}

// 数值转string
func numericalToString() {

	fmtSprintf()
	strconvFormat()
}

// 数值转string :strconv.Format
func strconvFormat() {
	var str5 string = strconv.FormatInt(int64(10), 10)
	fmt.Printf("type: %T value: %v\n", str5, str5) //type: string value: 10

	var str6 string = strconv.FormatFloat(3.0, 'f', 10, 64)
	fmt.Printf("type: %T value: %v\n", str6, str6) //	type: string value: 3.0000000000

	var str7 string = strconv.FormatBool(true)
	fmt.Printf("type: %T value: %v\n", str7, str7) //type: string value: true

	fmt.Println("------------------------------------------")
	str8 := strconv.Itoa(10)
	fmt.Printf("type: %T value: %v\n", str8, str8) //type: string value: 10

}

// 数值转string:fmt.Sprintf
func fmtSprintf() {

	//%d-十进制方式输出
	var str string = fmt.Sprintf("%d\n", 10)
	fmt.Printf("type: %T value: %v", str, str) //type: string value: 10

	//%f 有小数部分但无指数输出  %v默认格式输出
	var str1 string = fmt.Sprintf("%f\n", 3.0)
	fmt.Printf("type: %T value: %v", str1, str1) //type: string value: 3.000000

	//%t单词true或false
	var str2 string = fmt.Sprintf("%t\n", true)
	fmt.Printf("type: %T value: %v", str2, str2) //type: string value: true

	//%c 按字符方式输出
	var str3 string = fmt.Sprintf("%c\n", 'h')
	fmt.Printf("type: %T value: %v", str3, str3) //type: string value: h

	var str4 string = fmt.Sprintf("%d", 'h')
	fmt.Printf("type: %T value: %v", str4, str4) //type: string value: 104
}
